import axios from 'axios'

import appcfg from '@/app.config'
import store from '@/store'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API || '/',
  timeout: 5000
})

service.interceptors.request.use(
  config => {
    config.headers[appcfg.request.header.tokenKey] = store.state.user.token || ''
    return config
  },
  error => {
    console.error('Request error:' + error) // XXX: for debug
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  /** Return full HTTP informations. */
  // response => response,

  /** Return data */
  response => {
    const res = response.data
    if (res === undefined) {
      return Promise.reject(new Error('Response NULL data!'))
    } else if (res.code >= 400) {
      return Promise.reject(new Error(res.message || ('Code:' + res.code)))
    }
    return res
  },
  error => {
    console.error('Response error:' + error) // XXX: for debug
    return Promise.reject(error)
  }
)

export function send(url, config) {
  config = config || {}
  config['url'] = url
  if (!config['method']) {
    config['method'] = 'post'
  }
  return service(config)
}

export default {
  service,
  send
}

